/**
 * 
 */
package model;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;

import utils.StrUtils;

import database.IDbConnector;
import database.MySQLConnector;
import database.ValuedAttribute;

/**
 * Classe de gestion d'une partie
 * @author Aubry Pirian
 *
 */
public abstract class Match {
	
	private IDbConnector idbc;
	
	protected int game;							// jeu
	protected int id;							// numéro de la partie
	protected HashMap<String,Integer> start;	// début de la partie
	protected HashMap<String,Integer> end;		// fin de la partie
	protected String creator;					// identifiant du créateur
	protected int creatorId=-1;					// numéro du créateur
	//protected String misc;						// informations complémentaires
	
	public Match (int game, HashMap<String,Integer> start, HashMap<String,Integer> end, String creator) {
		this.connect();
		this.game = game;
		this.start = start;
		this.end = end;
		this.creator = creator;
	}
	
	public Match (int game, HashMap<String,Integer> start, HashMap<String,Integer> end, int creatorId) {
		this.connect();
		this.game = game;
		this.start = start;
		this.end = end;
		this.creatorId = creatorId;
	}
	
	private void connect() {
		try {
			this.idbc = new MySQLConnector(Params.DB_SERVER,Params.DB_USER,Params.DB_PASSWD,Params.DB_NAME);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		try {
			this.idbc.connect();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void save() {
		// Identification du membre
		if (this.creatorId==-1) {
			// Avec le login
			try {
				Member c = new Member(this.creator);
				this.creatorId = c.getId();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		// Sauvegarde de la partie
		LinkedList<ValuedAttribute> values = new LinkedList<ValuedAttribute>();
		try {
			if (this.id!=-1) values.add( new ValuedAttribute("id",this.id) );
			values.add( new ValuedAttribute("game",this.game) );
			values.add( new ValuedAttribute("start",StrUtils.toSQLDate(this.start)) );
			values.add( new ValuedAttribute("end",StrUtils.toSQLDate(this.end)) );
			values.add( new ValuedAttribute("creator",this.creatorId) );
			//values.add( new ValuedAttribute("misc",this.misc) );
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		try {
			this.idbc.insert(Params.MATCH_TABLE, values);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
	}

}
